//第一个代表操作 0=读取 1=添加 -1=删除,第二个参数代表存储的字段,第三个代表要存储的数据，
export function local(handle, field, data) {
  //先判断兼容性
  if (window.localStorage) {
    //公用判断是否存在的方法
    function isbeing() {
      return JSON.parse(localStorage.getItem(field));
    }

    function read() {
      let result = isbeing();
      return result
    }

    function add() {
      let result = isbeing();
      if(result==null){
        localStorage.setItem(field, JSON.stringify(data));
      }
      else{
        let index=null;

        if(result instanceof Array){
          for(let i in result){
            if(result[i].query==data.query){
              index=i;
              break;
            }
          }
          
          if(index!=null){
            result[index].time=data.time
            localStorage.setItem(field, JSON.stringify(result));
          }
          else{
            result.push(data)
            localStorage.setItem(field, JSON.stringify(result));
          }
        }
        else{
          localStorage.setItem(field, JSON.stringify(data));
        }
      }
    }

    function deletes() {
      let result = isbeing();
      if (result == null) {
        console.error(`要删除的字段不存在:${field}`);
      } else {
        localStorage.removeItem(field);
      }
    }

    const handlearr = new Map([
      [0, read],
      [1, add],
      [-1, deletes],
    ]);

    function handles() {
      if (handlearr.has(handle)) {
        let result = handlearr.get(handle || 0);
        return result();
      } else {
        console.error("请传入正确的handle参数");
      }
    }

    return handles();
  } else {
    console.error("该浏览器不支持localStorage存储");
  }
}
